package com.justech.eat.global;

import com.justech.eat.global.model.FormValidationResult;
import com.justech.eat.global.model.Result;
import com.justech.eat.global.model.ValidationError;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @program: eat-service
 * @description: 全局异常处理器
 * @author: feifei.li
 * @create: 2020-05-29 15:15
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({Exception.class})
    public Result handleHttpMessageNotReadableException(Exception e) {
        e.printStackTrace();
        return new Result(500, e.getMessage(), true);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({ConstraintViolationException.class})
    public Result handleConstraintViolationException(ConstraintViolationException exception){
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        ArrayList<ValidationError> formValidationResults = new ArrayList<>();
        for (ConstraintViolation<?> violation : constraintViolations) {
            ValidationError validationError = new ValidationError(violation.getPropertyPath().toString(),violation.getMessage());
            formValidationResults.add(validationError);
        }
        return new FormValidationResult(formValidationResults);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException argumentNotValidException) {
        BindingResult errorResult = argumentNotValidException.getBindingResult();
        ArrayList<ValidationError> formValidationResults = new ArrayList<>();
        if (errorResult.hasErrors()) {
            List<FieldError> fieldErrors = errorResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                formValidationResults.add(new ValidationError(fieldError.getField(), fieldError.getDefaultMessage()));
            }
        }
        return new FormValidationResult(formValidationResults);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        System.out.println(binder);
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }
}
